package com.example.stray_animal_management_system.interceptor;

import com.example.stray_animal_management_system.admin.service.UserLoginInfoService;
import com.example.stray_animal_management_system.entity.UserLoginInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * @description:登录拦截器 - 记录用户登录信息
 * @author: panpan
 * @time: 2025/11/9
 */

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private UserLoginInfoService userLoginInfoService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 只拦截登录接口
        if (request.getRequestURI().contains("/api/auth/login")) {
            // 登录成功后记录信息（这里需要在登录成功后调用）
            return true;
        }
        return true;
    }

    /**
     * 记录用户登录信息
     * 在登录成功后调用此方法
     */
    public void recordLoginInfo(HttpServletRequest request, Integer userId, String username) {
        try {
            UserLoginInfo loginInfo = new UserLoginInfo();
            loginInfo.setUserId(userId != null ? userId.longValue() : null);
            loginInfo.setUsername(username);

            // 获取IP地址
            String ipAddress = getIpAddress(request);
            loginInfo.setIpAddress(ipAddress);

            // 获取User-Agent信息
            String userAgent = request.getHeader("User-Agent");
            if (userAgent != null) {
                // 解析浏览器信息
                String browser = parseBrowser(userAgent);
                loginInfo.setBrowser(browser);

                // 解析操作系统信息
                String os = parseOS(userAgent);
                loginInfo.setOs(os);

                // 解析设备信息
                String device = parseDevice(userAgent);
                loginInfo.setDevice(device);
            }

            // 获取登录地点（这里可以使用IP地址查询地理位置，简化处理）
            String location = getLocationByIp(ipAddress);
            loginInfo.setLocation(location);

            // 保存登录信息
            userLoginInfoService.saveLoginInfo(loginInfo);
        } catch (Exception e) {
            // 记录登录信息失败不影响登录流程
            System.err.println("记录登录信息失败：" + e.getMessage());
        }
    }

    /**
     * 获取客户端IP地址
     */
    private String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 如果是多级代理，取第一个IP
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }
        return ip;
    }

    /**
     * 解析浏览器信息
     */
    private String parseBrowser(String userAgent) {
        if (userAgent.contains("Edg")) {
            return "Microsoft Edge";
        } else if (userAgent.contains("Chrome")) {
            return "Google Chrome";
        } else if (userAgent.contains("Firefox")) {
            return "Mozilla Firefox";
        } else if (userAgent.contains("Safari") && !userAgent.contains("Chrome")) {
            return "Safari";
        } else if (userAgent.contains("Opera") || userAgent.contains("OPR")) {
            return "Opera";
        } else if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
            return "Internet Explorer";
        }
        return "Unknown Browser";
    }

    /**
     * 解析操作系统信息
     */
    private String parseOS(String userAgent) {
        if (userAgent.contains("Windows NT 10.0")) {
            return "Windows 10";
        } else if (userAgent.contains("Windows NT 6.3")) {
            return "Windows 8.1";
        } else if (userAgent.contains("Windows NT 6.2")) {
            return "Windows 8";
        } else if (userAgent.contains("Windows NT 6.1")) {
            return "Windows 7";
        } else if (userAgent.contains("Mac OS X")) {
            return "macOS";
        } else if (userAgent.contains("Linux")) {
            return "Linux";
        } else if (userAgent.contains("Android")) {
            return "Android";
        } else if (userAgent.contains("iPhone") || userAgent.contains("iPad")) {
            return "iOS";
        }
        return "Unknown OS";
    }

    /**
     * 解析设备信息
     */
    private String parseDevice(String userAgent) {
        if (userAgent.contains("Mobile")) {
            if (userAgent.contains("iPhone")) {
                return "iPhone";
            } else if (userAgent.contains("iPad")) {
                return "iPad";
            } else if (userAgent.contains("Android")) {
                return "Android Mobile";
            }
            return "Mobile Device";
        }
        return "Desktop";
    }

    /**
     * 根据IP地址获取地理位置（简化处理，实际可以使用IP地址库）
     */
    private String getLocationByIp(String ipAddress) {
        // 这里可以集成IP地址查询服务，如高德地图、百度地图等
        // 简化处理，返回IP地址
        if (ipAddress == null || ipAddress.isEmpty()) {
            return "未知";
        }
        // 本地IP
        if (ipAddress.startsWith("127.") || ipAddress.startsWith("192.168.") || ipAddress.startsWith("10.")) {
            return "本地网络";
        }
        // 这里可以调用IP地址查询API获取真实地理位置
        return "未知位置";
    }
}
